const messageDAO = require('./models/message.js');
const msgpack = require('./helper/framedmsgpack.js')
/**
 * 
 * 推送业务
 * [pushMsg description]
 * @param {[type]} req [description]
 * @param {[type]} res [description
 * @param {[type]} config [description]
 * @param {[type]} msg [descriptions]
 * @param {[type]} connections [description]
 * @return {[type]} [description]
*/
function pushMsg(req,res,config,deviceId,msg,connections){
    if(config.APP_ID !== req.body.appId || config.APP_SECRET !== req.body.secret || !deviceId ||deviceId === ''){
        res.status(401).json({
            code:401,
            status: 'Unauthorized',
            message: 'request validation fail.'
        })
        return ;
    }
    //由于bodyParse中阿金解析本身就是json对象就没必要再次装换
    if(!(msg instanceof Object)){
        msg = eval("(" + msg + ")");//转换msg对象JSON.parse(msg)
    }

    var message = {
        msgId:msg.id,
        msgType:msg.messageType,
        title:msg.title,
        target:deviceId,
        isWrap:msg.isWrap
    }
    if(msg.extras){
        //存在扩展信息情况，例如推送公告
        message.extras = msg.extras;
    }
    console.log('step 保存日志: ' + message.msgId);
    /**
     * 根据设备发送msg
     * 
    */
    console.log('step2 发送消息--> %s :%s,队列长度：%s',(typeof deviceId),deviceId,connections.keys.length);
    var socket = connections.get(deviceId);
    if(socket){
        //mongo更新成功状态
        message.receive = true;
        messageDAO.save(message,function(err){
            if(err){
                console.log('插入message对象异常: ' + err);
            }
            socket.write(msgpack.packWithType(msg,1));//推送给客户端APP
            res.status(200).json({
                code:200,
                status:'success',
                message:'推送成功'
            })
        })
    }else{
        console.log('此设备未保持长连接，没关系，登录长连接后他会去平台拉取离线消息');
        //mongo跟新失败状态
        message.receive = false;
        messageDAO.save(message,function(err){
            if(err){
                console.log('插入message对象异常： ' + err);
            }
        });
        res.status(200).json({
            code:"304",
            status:'failure',
            message:'推送失败!原因:此设备未保持长连接'

        })
    }
}
/***commonjs interface**/

module.exports = function apiContructor(app,connections,qqwry,config){
    app.get('/instant/connections',function(req,res){
        var size = connections.size();
        res.status(200).json({
            code:200,
            status:'v',
            message:'connection size' + size
        })
    });
    app.post('/instant/pushMsg',function(req,res){
        var ip = req.ip;
        if(qqwry){
            ip = qqwry.searchIP(req.ip);//解析IP地址

        }
        //step1获取msg deviceId
        var msg = req.body.msg;
        var deviceId = req.body.deiceId;
        pushMsg(req,res,config,deviceId,msg.connections);
    })
}
